import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card, Button, message, Table, Row,
} from 'antd';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import AddModal from './addModal';
import EditModal from './editModal';
import DetailModal from './detailModal';
import SendModal from './sendModal';
import { filterAuth } from "@/support/common";
import PropTypes from "prop-types";
import styles from '../../../components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import * as G from '../../../utils/common';
import ExportModal from './exportModal';
import TaskModal from './taskCenter/index';

const mapStateToProps = (state: any) => ({
  collectionConfiguration: state.collectionConfiguration,
  loading: state.loading.effects['collectionConfiguration/postFetchPage'],
});
let pageObj = {};
class CollectionConfiguration extends PureComponent<any, any> {

  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {
    
      },
      pagination: {
        pageNo: 1,
        pageSize: 10,
      },
      addVisible: false,
      editVisible: false,
      detailVisible: false,
      sendVisible: false,
      statusData: [{label: '未下发',value: 0},{label: '下发成功',value: 2},{label: '下发失败',value: 1}],//配置状态
      msg: '',
      exportVisible: false,//导出字段
      taskCenterVisible: false,//任务中心
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;
    dispatch({
      type: "collectionConfiguration/postFetchPage",
      payload: { url: "/data/collection/config/list" , ...formValues, ...pagination  }
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'collectionConfiguration/initData'
    });
  }

  handleAdd = () => {
    this.getTime();
    this.setState({
      addVisible: true,
    })
  }
  getTime = () =>{ // 获取当前时间
    var openTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")   	
   console.log('sendTime', openTime)
    const s = '采集配置' + openTime
    this.setState({
        msg: s
    })
  }
  closeAddModal = () => {
    this.setState({
      addVisible: false,
    })
  }
  handleSend = (record:any) =>{
    this.setState({
      sendVisible: true,
    })
    this.sendForm.setData(record);
    this.sendForm.updateData();
  }
  closeSendModal = () => {
    this.setState({
      sendVisible: false,
    })
    this.props.dispatch({
      type: "collectionConfiguration/postFetchPage",
      payload: { url: "/data/collection/config/list" }
  })
  }
  handleEdit = (record:any) => {
    this.setState({
      editVisible: true,
    })
    this.editForm.setData(record);
  }

  closeEditModal = () => {
    this.setState({
      editVisible: false,
    })
  }
  handleDetail = (record:any) => {
    this.setState({
      detailVisible: true,
    })
    this.detailForm.setData(record);
  }

  closeDetailModal = () => {
    this.setState({
      detailVisible: false,
    })
  }

/**
   * 参数校验&分页入参处理
   * @param fieldsValue
   */
 handleFieldsValue = (fields: any) => {
  console.log(fields)
  if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
    const [start, end] = fields.handleTimeRange;
      fields['configStartTime'] = moment(start).valueOf();
      fields['configEndTime'] = moment(end).valueOf();
      delete fields['handleTimeRange'];
    return fields;
  } else {
    return fields;
  }
};
handleFormReset = () => {
  this.searchForm.current?.resetFields();
  this.setState({
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 10,
    },
  });
};
handleRecory = (record: any) => {
  const { dispatch } = this.props;
  let param = {};
  param['id'] = record.id;
  if(record.vin){
    param['vin'] = record.vin
  }else{
    param['vehicleId'] = record.vehicleId
  }
  dispatch({
    type: 'collectionConfiguration/getDataWithRes',
    payload: { url: `/data/collection/config/recovery`, ...param},
    callback: (response: any) => {
      if (response.statusCode === '0') {
        message.success('恢复采集配置成功');
        dispatch({
          type: "collectionConfiguration/postFetchPage",
          payload: { url: "/data/collection/config/list" }
      })
      this.sendForm.updateData();
      }
    },
  });
  };
  handleDelete = (id: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'collectionConfiguration/getData',
      payload: { url: `/data/collection/config/delete/${id}`},
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          dispatch({
            type: "collectionConfiguration/postFetchPage",
            payload: { url: "/data/collection/config/list" }
        })
        }
      },
    });
  };
    // 分页时触发
    tableOnChange = (pagination: any) => {
      const current = pagination.current;
      this.setState(
        {
          pagination: {
            pageNo: current,
            pageSize: pagination.pageSize,
          },
        },
        () => {
          this.handleFreshPage();
        },
      );
    };
    handleFreshPage = () => {
      const { dispatch } = this.props;
      const { formValues, pagination } = this.state;
      dispatch({
        type: 'collectionConfiguration/postFetchPage',
        payload: {
          url: '/data/collection/config/list',
          ...formValues,
          ...pagination,
        },
      });
    };

  handleExport = () => {
    this.setState({
      exportVisible: true,
    })
  }
  closeExportModal = () => {
    this.setState({
      exportVisible: false,
    })
  }
    handleTaskCenterModalShow = () => {
      this.setState({
        taskCenterVisible: true,
      });
    };
  
    closeTaskCenterModal = () => {
      this.setState({
        taskCenterVisible: false,
      });
    };
  render() {
    const { collectionConfiguration: { pageData: { list, pagination } }, loading, location: { pathname = '/' } } = this.props;
    pageObj = pagination;
    const { formValues, addVisible, editVisible, sendVisible,detailVisible, statusData,msg,exportVisible,taskCenterVisible, } = this.state;
    const columns = [
      {
        title: '采集配置名称',
        dataIndex: 'collectName'
      },
      {
        title: '采集频率（秒）',
        dataIndex: 'collectFrequency'
      },
      {
        title: '采集周期',
        dataIndex: 'cycleValue',
        render: (text:any, record:any) => {
          if (record.collectCycle == 0) {
            return (
               text + '天'
            );
          }else if(record.collectCycle == 1){
            return (
              text + '公里'
           );
          }
          return text;
        },
      },
      {
        title: '采集车辆',
        dataIndex: 'vin',
        render: (text:any, record:any) => {
          if (text) {
            return (
               text 
            );
          }else {
            return (
              record.vehicleGroupName
           );
          }
        },
      },
      {
        title: '配置状态',
        dataIndex: 'configStatus',
        render: (text: any) => {
          switch (String(text)) {
            case '0':
              return '未下发';
            case '1':
              return '下发失败';
            case '2':
              return '下发成功';
            default:
              break;
          }
          return text;
        }
      },
      {
        title: '最后下发配置时间',
        dataIndex: 'configTime',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 230,
        render: (text: any, record: any) => {
          const btns = [];
          const detailBtn = {
            title: '查看',
            key: 'show',
            auth: "collectionConfiguration_show",
            onConfirm: () => this.handleDetail(record),
          };
          const sendBtn = {
            title: '下发配置',
            key: 'send',
            auth: "collectionConfiguration_send",
            onConfirm: () => this.handleSend(record),
        };
          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: "collectionConfiguration_edit",
            onConfirm: () => this.handleEdit(record),
        };
        const deleteBtn = {
          title: '删除',
          key: 'delete',
          auth: "collectionConfiguration_delete",
          message: '确认删除吗？',
          Popconfirm: true,
          onConfirm: () => this.handleDelete(record.id),
       };
       const recoveryBtn =  {
        title: '恢复配置',
        key: 'recovery',
        auth: "collectionConfiguration_recovery",
        message: '采集配置生效中，确认恢复吗？',
        Popconfirm: true,
        onConfirm: () => this.handleRecory(record),
       };
       const reSendBtn = {
        title: '重新下发',
        key: 'reSend',
        auth: "collectionConfiguration_reSend",
        onConfirm: () => this.handleSend(record),
       };
       btns.push(detailBtn);
       if(record.configStatus == 0){
        btns.push(sendBtn,editBtn,deleteBtn)
       }
       else if(record.configStatus == 2){
        btns.push(recoveryBtn,)
       }else if(record.configStatus == 1){
        btns.push(reSendBtn,editBtn,deleteBtn)
       }
      //  if(record.configStatus == 0){
      //   btns.push(sendBtn,editBtn,detailBtn,deleteBtn)
      //  }
      //  else if(record.configStatus == 2){
      //   btns.push(recoveryBtn,detailBtn)
      //  }else if(record.configStatus == 1){
      //   btns.push(reSendBtn,editBtn,detailBtn,deleteBtn)
      //  }
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    };
    const searchItems = [
      {
        type: 'input',
        title: '采集配置名称',
        key: 'collectName',
      },
      {
        type: 'input',
        title: '采集频率',
        key: 'collectFrequency',
      },
      {
        type: 'select',
        title: '配置状态',
        key: 'configStatus',
        selectOptions: statusData,
        keyValue: ["value", "label"],
      },
      {
        title: '下发配置时间',
        type: 'rangePicker',
        key: 'handleTimeRange',
        format: 'YYYY-MM-DD',
        showTime: false,
        customStyle: 8,
        rules: [{ required: false, message: '下发配置时间非必选!' }],
      },
    ];
    return (
      <div>
        <Card bordered={false}>
        <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'collectionConfiguration/postFetchPage', url: '/data/collection/config/list' }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.handleFieldsValue}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div>
            <Row>
          {
            filterAuth("collectionConfiguration_toAdd", this.context.permissions, pathname) ? (
              <div style={{padding: '5px'}}>
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => this.handleAdd()}
                >
                  新增
                </Button>
              </div>
            ) : null
          }
          {
            filterAuth("collectionConfiguration_toImport", this.context.permissions, pathname) ? (
              <div style={{padding: '5px'}}>
                <Button
                  size="small"
                  type="primary"
                  onClick={() => this.handleExport()}
                >
                  导出字段
                </Button>
              </div>
            ) : null
          }
          {
            filterAuth("collectionConfiguration_taskCenter", this.context.permissions, pathname) ? (
              <div style={{padding: '5px'}}>
                <Button
                  size="small"
                  type="primary"
                  onClick={() => this.handleTaskCenterModalShow()}
                >
                  任务中心
                </Button>
              </div>
            ) : null
          }
          </Row>
          </div>
           <Table
            size="small"
            rowKey={record => record.id}
            dataSource={list ? list : []}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.tableOnChange}
            scroll={{ x: 'max-content'  }}
          />
          {/* <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'collectionConfiguration/postFetchPage', url: '/data/collection/config/list' }}
            formValues={formValues}
          /> */}
        </Card>
        <AddModal
          msg={msg}
          modalVisible={addVisible}
          closeModal={this.closeAddModal}
        />
        <EditModal
          onRef={(val: any) => this.editForm = val}
          modalVisible={editVisible}
          closeModal={this.closeEditModal}
          pageObj={pageObj}
          formValues={formValues}
        />
        <DetailModal
          onRef={(val: any) => this.detailForm = val}
          modalVisible={detailVisible}
          closeModal={this.closeDetailModal}
          pageObj={pageObj}
          formValues={formValues}
        />
        <SendModal
          onRef={(val: any) => this.sendForm = val}
          modalVisible={sendVisible}
          closeModal={this.closeSendModal}
          pageObj={pageObj}
          formValues={formValues}
        />
        <ExportModal
          modalVisible={exportVisible}
          closeModal={this.closeExportModal}
        />
         <TaskModal
          onRef={(val: any) => (this.taskCenterModal = val)}
          modalVisible={taskCenterVisible}
          closeModal={this.closeTaskCenterModal}
        />
      </div >
    )
  }

}
export default connect(mapStateToProps)(CollectionConfiguration);